﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Threading;
using System.Net.Sockets;
using System.Net;


namespace WebProxy_MMTNC
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        /// <summary>
        /// Hàm này dùng để tạo ra 1 socket server lắng nghe kết nối
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        public void TaoSocKet(int port)
        {
            try
            {
                TcpListener SocketServer = new TcpListener(port);
                MessageBox.Show("Server đang lắng nghe ở port" + port);
                SocketServer.Start();
                while (true)
                {
                    // Chấp nhận kết nối tại port truyền vào
                    try
                    {
                        Socket socket = SocketServer.AcceptSocket();
                        //// sau khi chấp nhận kết nối, 
                        //clsProxyConnection proxy = new clsProxyConnection(socket);
                        //Thread thrd = new Thread(new ThreadStart(proxy.Run));
                        //thrd.Start();
                        //// While the thread is running, the main program thread will loop around
                        //// and listen for the next connection request.
                        WebProxy2 webproxy = new WebProxy2(socket);
                        Thread thread = new Thread(new ThreadStart(webproxy.run));
                        thread.Start();
                    }
                    catch
                    {
                        MessageBox.Show("không chấp nhận kết nối tại port" + port.ToString());
                    }

                }
            }
            catch (IOException e)
            {
                MessageBox.Show("Lỗi" + e.Message.ToString());
            }

        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void btnKhoiTao_Click(object sender, EventArgs e)
        {
            try
            {
                if (!string.IsNullOrEmpty(txtPort.Text))
                {
                    TaoSocKet(int.Parse(txtPort.Text));
                    MessageBox.Show("Tạo kết nối thành công");
                }
                else
                {
                    MessageBox.Show("Bạn phải nhập số nguyên vào ô này");
                    txtPort.Text = "";
                }
            }
            catch
            {
                MessageBox.Show("Bạn phải nhập số nguyên vào ô này");
                txtPort.Text = "";
            }
        }






        //}
        //class WebProxy2
        //{
        //    Socket clientSocket;
        //    Byte[] read = new byte[1024];
        //    Byte[] Buffer = null;
        //    Encoding UTF8 = Encoding.UTF8;
        //    const string HTTP_VERSION = "HTTP/1.0";
        //    const string CRLF = "\r\n";
        //    Byte[] RecvBytes = new Byte[4096];
        //    public WebProxy2(Socket socket)
        //    {
        //        this.clientSocket = socket;
        //    }
        //    public void run()
        //    {
        //        String clientmessage = " ", sURL = " ";
        //        int bytes = readmessage(read, ref clientSocket, ref clientmessage);
        //        if (bytes == 0)
        //        {
        //            return;
        //        }
        //        int index1 = clientmessage.IndexOf(' ');
        //        int index2 = clientmessage.IndexOf(' ', index1 + 1);
        //        if ((index1 == -1) || (index2 == -1))
        //        {
        //            throw new IOException();
        //        }

        //        Label.l
        //        Console.WriteLine("Connecting to Site: {0}", clientmessage.Substring(index1 + 1, index2 - index1));
        //        Console.WriteLine("Connection from {0}", clientSocket.RemoteEndPoint);
        //        string part1 = clientmessage.Substring(index1 + 1, index2 - index1);
        //        int index3 = part1.IndexOf('/', index1 + 8);
        //        int index4 = part1.IndexOf(' ', index1 + 8);
        //        int index5 = index4 - index3;
        //        sURL = part1.Substring(index1 + 4, (part1.Length - index5) - 8);
        //        try
        //        {
        //            IPHostEntry IPHost = Dns.Resolve(sURL);
        //            Console.WriteLine("Request resolved: ", IPHost.HostName);
        //            string[] aliases = IPHost.Aliases;
        //            IPAddress[] address = IPHost.AddressList;
        //            Console.WriteLine(address[0]);
        //            IPEndPoint sEndpoint = new IPEndPoint(address[0], 80);
        //            Socket IPsocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        //            IPsocket.Connect(sEndpoint);
        //            if (IPsocket.Connected)
        //                Console.WriteLine("Socket connect OK");
        //            string GET = clientmessage;
        //            Byte[] ByteGet = UTF8.GetBytes(GET);
        //            IPsocket.Send(ByteGet, ByteGet.Length, 0);
        //            Int32 rBytes = IPsocket.Receive(RecvBytes, RecvBytes.Length, 0);
        //            Console.WriteLine("Recieved {0}", +rBytes);
        //            //Buffer = RecvBytes;
        //            String strRetPage = null;
        //            strRetPage = strRetPage + UTF8.GetString(RecvBytes, 0, rBytes);
        //            while (rBytes > 0)
        //            {
        //                rBytes = IPsocket.Receive(RecvBytes, RecvBytes.Length, 0);
        //                strRetPage = strRetPage + UTF8.GetString(RecvBytes, 0, rBytes);
        //            }
        //            IPsocket.Shutdown(SocketShutdown.Both);
        //            IPsocket.Close();
        //            sendmessage(clientSocket, strRetPage);
        //        }
        //        catch (Exception exc2)
        //        {
        //            Console.WriteLine(exc2.ToString());
        //        }
        //    }
        //    private int readmessage(byte[] ByteArray, ref Socket s, ref String clientmessage)
        //    {
        //        int bytes = s.Receive(ByteArray, 1024, 0);
        //        string messagefromclient = Encoding.ASCII.GetString(ByteArray);
        //        clientmessage = (String)messagefromclient;
        //        return bytes;
        //    }
        //    private void sendmessage(Socket s, string message)
        //    {
        //        Buffer = new Byte[message.Length + 1];
        //        int length = UTF8.GetBytes(message, 0, message.Length, Buffer, 0);
        //        s.Send(Buffer, length, 0);
        //    }

    }
    

}
